// Program: tty
// Description: Creates TTY devices, and multiplexes them onto the screen.
//

//
// main.cc -- Defines the main startup routine, and runloop.
//

#include <UdevFilesystem.h>
#include "Tty.h"
#include "serial.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <jimix/ResourceManager.h>

LocalTty *activeTty;
SerialTty *serialTty1;
SerialTty *serialTty2;
Tty *ttys[32];
int nttys = 0;

extern "C" void yield();

extern void keyboard_init();

void set_active_tty(int a)
{
  activeTty->setActive(false);
  activeTty = (LocalTty*)ttys[a];
  activeTty->setActive(true);
}

int main(char argc, char **argv)
{
  
  u32int devfs = requestResource("devfs");
  u32int resourceManager = requestResource("ResourceManager");
  char *name = (char*)"tty";
  char *shared_name = (char*)callResource(resourceManager, ResourceManager_IF::share, name, 4);
  
  // Make 4 local ttys initially.
  for (int i = 0; i < 3; i++)
  {
    char *str = new char[10];
    sprintf(str, "/dev/tty%d", i+1);
    ttys[i] = new LocalTty(80,25, str);
    int major = -1;
    int minor = i+1;
    callResource(devfs, UdevFilesystem_IF::makedev, shared_name, false, (major<<16)|minor, ttys[i]->resource);
  }
  
  callResource(resourceManager, ResourceManager_IF::unshare, shared_name, NULL, 0);
  
  char *nameC = (char*)"console";
  char *str = (char*)"/dev/console";
  char *shared_nameC = (char*)callResource(resourceManager, ResourceManager_IF::share, nameC, 8);
  
  ttys[3] = new LocalTty(80,25, str);
  int major = -1;
  int minor = -1;
  callResource(devfs, UdevFilesystem_IF::makedev, shared_nameC, false, (major<<16)|minor, ttys[3]->resource);
  
  callResource(resourceManager, ResourceManager_IF::unshare, shared_nameC, NULL, 0);
  
  char *nameS = (char*)"ttyS";
  char *shared_nameS = (char*)callResource(resourceManager, ResourceManager_IF::share, nameS, 5);
  
  // Make 2 serial ttys.
  for (int i = 0; i < 2; i++)
  {
    char *str = new char[11];
    sprintf(str, "/dev/ttyS%d", i+1);
    ttys[i+4] = new SerialTty(str, (i==0)?SERIAL_COM1:SERIAL_COM2);
    
    major = -1;
    minor = i+1;
    callResource(devfs, UdevFilesystem_IF::makedev, shared_nameS, false, (major<<16)|minor,
                 ttys[i+4]->resource);
  }
  
  callResource(resourceManager, ResourceManager_IF::unshare, shared_nameS, NULL, 0);
  
  serialTty1 = (SerialTty*)ttys[4];
  serialTty2 = (SerialTty*)ttys[5];
  ttys[0]->setActive(true);
  ttys[0]->write((char*)"Welcome to tty1\n");
  ttys[1]->write((char*)"Welcome to tty2\n");
  ttys[2]->write((char*)"Welcome to tty3\n");
  //ttys[3]->write("Welcome to tty4\n");
//   ttys[4]->write((char*)"Welcome to ttyS1\n");
//   ttys[5]->write((char*)"Welcome to ttyS2\n");
  activeTty = (LocalTty*) (ttys[0]);
  
  keyboard_init();
  serial_init();

  for(;;)
  {
    serial_handler(5);
    yield();
  }
}
